package com.example.datapedestal.utils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author: ThinkPad
 * @since: 2023/10/27 14:02
 * @description:
 */
public class EntityReflectionUtils<T> {
    /**
     * 使用反射为实体类的字段赋值
     *
     * @param object     实体类对象
     * @param fieldValueObject 字段名和值的映射 支持map和实体
     */
    public static void setFieldValues(Object object, Object fieldValueObject)  {
        Class<?> clazz = object.getClass();
        if (fieldValueObject instanceof Map) {
            // 处理 Map 类型的字段赋值
            Map<?, ?> fieldValueMap = (Map<?, ?>) fieldValueObject;
            for (Map.Entry<?, ?> entry : fieldValueMap.entrySet()) {
                String fieldName = String.valueOf(entry.getKey());
                Object value = entry.getValue();
                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    field.set(object, value);
                }catch (Exception e){
                    System.out.println(e);
                }
            }
        } else {
            // 处理实体类类型的字段赋值
            Class<?> fieldValueClass = fieldValueObject.getClass();
            // 获取字段值对象的所有字段
            Field[] fields = fieldValueClass.getDeclaredFields();
            for (Field field : fields) {
                // 设置字段可访问性为true，以便获取和设置私有字段的值
                field.setAccessible(true);
                String fieldName = field.getName();
                try{
                    Object value= field.get(fieldValueObject);
                    Field field1 = clazz.getDeclaredField(fieldName);
                    field1.setAccessible(true);
                    field1.set(object, value);
                }catch (Exception e){
                    System.out.println(e);
                }

            }
        }
    }
    //设置指定表并且获取指定字段值
    public static Object getField(Object ConfigListForm,String name) throws Exception {
        Field field = ConfigListForm.getClass().getDeclaredField(name);
        field.setAccessible(true);
        Object value = field.get(ConfigListForm);
        return value;
    }

    //设置指定表并且给指定字段赋值
    public static void setField(Object obj,String name,Object value) throws Exception {
        Class clazz=obj.getClass();
        Field field = clazz.getDeclaredField(name);
        field.setAccessible(true);
        //实例化实体类并且赋值
        field.set(obj,value);
    }
}
